import * as service from '../services/login';
import {decode} from 'jsonwebtoken';
import {routerRedux} from 'dva/router';
export default {
  namespace:'login',
  state:{
      isLogin:true,//是否正在注册
      errorInfo:'',//放着报错信息
      userInfo:null//如果用户登录之后，会把用户信息放在这里
  },

  subscriptions: {
      setup({dispatch,history}) {
          history.listen(({pathname,query}) => {
              if (pathname == '/login') {

              } else if (pathname == '/signup') {

              }
          });
      }
  },
  effects:{
      *signup({payload},{call,put}){
        yield call(service.signup,payload);
        yield put({type:'save',payload:{isLogin:true}});
      },
      *login({payload},{call,put}){
        const token=yield call(service.login,payload);
        //解开token 
        const userInfo = decode(token);
        yield put({type:'save',payload:{userInfo}});  //放置到仓库     
        localStorage.setItem('token',token);    //本地存储起来
        yield put(routerRedux.push('/admin'));  //登陆成功,跳转到后台管理页面
      },
      
      *loadUser({payload},{call,put}) {
            //从本地缓存获取token
            let token=localStorage.getItem('token');
            //如果存在，进行解构出来
            if (token) {
                const user = decode(token);
                yield put({type:'setUserInfo',payload:user});
            }
            //不存在跳转到登陆页面进行登陆
             else {
                yield put(routerRedux.push('/login'));
            }
        }
  },
  reducers:{
    save(state,action){
      return {...state,...action.payload};
    }
  }
}